//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;
        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}


document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            // 移除所有导航链接的激活状态
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            // 移除所有内容区域的激活状态
            contentAreas.forEach(content => content.classList.remove('active'));
            // 为当前点击的导航链接添加激活状态
            this.classList.add('active');
            // 获取目标内容区域的 ID
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                // 为目标内容区域添加激活状态
                targetContent.classList.add('active');
            }
        });
    });
    const tables = document.querySelectorAll('.adminManagement-table');
    //分页
    $(document).ready(function () {
        const rowsPerPage = 4; // 每页显示的行数，需与后端默认 pageSize 一致
        const $tableBody = $('#table-body');
        const $pageNav = $('#pageNav');
        let currentPage = 1;
        let totalPages = 1;

        // ❗️ 事件委托：处理所有动态按钮（禁言、删除、编辑）
        $tableBody.on('click', '.static, .deletebtn, .editbtn', function (event) {
            const $btn = $(event.target);
            const action = $btn.attr('class').split(' ')[0]; // 获取按钮类名（static/deletebtn/editbtn）
            const userId = $btn.closest('tr').data('user-id'); // 统一通过data属性获取用户ID

            switch (action) {
                case 'static': // 禁言按钮
                    handleMuteUser($btn, userId);
                    break;
                case 'deletebtn': // 删除按钮
                    handleDeleteUser($btn, userId);
                    break;
                case 'editbtn': // 编辑按钮
                    handleEditUser(userId);
                    break;
            }
        });

        // 初始化加载第一页数据
        loadPage(1);

        // 加载指定页数据
        function loadPage(pageNumber) {
            currentPage = pageNumber;

            $.ajax({
                type: 'GET',
                url: '/admin/getUsersFromManagerWithPaging', // 后端分页接口
                data: {
                    pageNum: pageNumber,
                    pageSize: rowsPerPage
                },
                success: function (response) {
                    console.log('后端返回数据:', response);
                    const userList = response.list || [];
                    totalPages = response.totalPage || 1;
                    $tableBody.empty();
                    if (userList.length > 0) {
                        userList.forEach(user => {
                            console.log(user.email)
                            const row = $('<tr>')

                                .attr('data-user-id', user.id)
                                .append(
                                    $('<td>').html(`<input type="checkbox" class="rowCheckbox" data-user-id="${user.id}">`),
                                    $('<td>').html(`<img alt="${user.username}" src="${user.avatar}" class="img-thumbnail" style="width: 50px; height: 50px;">`),
                                    $('<td>').text(user.username),
                                    $('<td>').text(user.password),
                                    $('<td>').text(user.email),
                                    $('<td>').text(user.gender || '未知'), // 确保字段存在
                                    $('<td>').html(`<button class="static">${user.status}</button>`),
                                    $('<td>').html(`
                                    <button class="deletebtn btn btn-danger btn-sm" data-user-id="${user.id}">删除</button>
                                    <button class="editbtn btn btn-primary btn-sm" data-user-id="${user.id}">编辑</button>
                                `)
                                );
                            $tableBody.append(row);
                        });
                        initSelectAll();
                        $pageNav.show();

                    } else {
                        $pageNav.hide();
                    }

                    updatePagination();

                },
                error: function (error) {
                    console.error('分页数据加载失败:', error);
                    $pageNav.hide();
                }
            });
            $('#checkkey-button').click(function () {
                const searchTerm = $('#check').val();
                if (searchTerm.trim() !== '') {
                    // 发送AJAX请求
                    $.ajax({
                        type: 'GET',
                        url: '/admin/behindManagerUser', // 后端查询用户的API
                        data: {
                            query: searchTerm,
                            pageNum: currentPage
                        },
                        success: function (response) {
                            // 清空表格
                            $('#table-body').empty();

                            // 解析HTML响应
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(response, 'text/html');

                            // 获取搜索关键词（转为小写用于不区分大小写匹配）
                            const searchTerm = $('#check').val().trim().toLowerCase();

                            // 从HTML中提取用户行，并过滤包含关键词的行
                            const userRows = Array.from(doc.querySelectorAll('#table-body tr'))
                                .filter(row => {
                                    // 获取用户名单元格内容（第3列）
                                    const usernameCell = row.querySelector('td:nth-child(3)');
                                    return usernameCell && usernameCell.textContent.toLowerCase().includes(searchTerm);
                                });

                            if (userRows.length === 0) {
                                const notice = document.getElementById('notice');
                                notice.style.display = 'block';
                                return;
                            } else {
                                const notice = document.getElementById('notice');
                                notice.style.display = 'none';
                            }


                            // 遍历过滤后的行并添加到表格
                            userRows.forEach(row => {
                                const userId = row.getAttribute('th:data-user-id') || row.getAttribute('data-user-id');
                                if (!userId) return;

                                const cells = row.querySelectorAll('td');
                                const avatarImg = cells[1].querySelector('img');
                                const avatarUrl = avatarImg ? avatarImg.getAttribute('th:src') || avatarImg.src : 'https://picsum.photos/200/150';

                                const newRow = $('<tr>')
                                    .attr('data-user-id', userId)
                                    .append(`<td><input type="checkbox" class="rowCheckbox" data-user-id="${userId}"></td>`)
                                    .append(`<td><img alt="" src="${avatarUrl}"></td>`)
                                    .append(`<td>${cells[2].textContent}</td>`)
                                    .append(`<td>${cells[3].textContent}</td>`)
                                    .append(`<td>${cells[4].textContent}</td>`)
                                    .append(`<td>${cells[5].textContent}</td>`)
                                    .append(`<td><button class="static">${cells[6].textContent}</button></td>`)
                                    .append(`<td>
                <button class="deletebtn" data-user-id="${userId}">删除</button>
                <button class="editbtn nameedit" data-user-id="${userId}">编辑</button>
            </td>`);

                                $('#table-body').append(newRow);
                            });
                        },
                        error: function (error) {
                            console.error('查询失败', error);
                            showCustomAlert('查询失败，请稍后重试', 3000);
                        }
                    });
                } else {
                    showCustomAlert('请输入查询关键词', 3000);
                }
            });
        }

        // 更新分页导航
        function updatePagination() {
            $pageNav.empty(); // 清空原有导航

            // 上一页按钮
            const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
            if (currentPage === 1) {
                $prevBtn.addClass('disabled'); // 第一页时禁用
            } else {
                $prevBtn.click(function (e) {
                    e.preventDefault();
                    loadPage(currentPage - 1);
                });
            }
            $pageNav.append($prevBtn);

            // 页码按钮（显示当前页附近的页码）
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // 左侧省略号
            if (startPage > 1) {
                $pageNav.append($('<span>').text('...'));
            }

            // 页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const $pageBtn = $('<a href="#" class="num">').text(i);
                if (i === currentPage) {
                    $pageBtn.addClass('active'); // 高亮当前页
                } else {
                    $pageBtn.click(function (e) {
                        e.preventDefault();
                        loadPage(i);
                    });
                }
                $pageNav.append($pageBtn);
            }

            // 右侧省略号
            if (endPage < totalPages) {
                $pageNav.append($('<span>').text('...'));
            }

            // 下一页按钮
            const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
            if (currentPage === totalPages) {
                $nextBtn.addClass('disabled'); // 最后一页时禁用
            } else {
                $nextBtn.click(function (e) {
                    e.preventDefault();
                    loadPage(currentPage + 1);
                });
            }
            $pageNav.append($nextBtn);
        }
    });

    function initSelectAll() {
        const selectAll = document.querySelector('.selectAll');
        const rowCheckboxes = document.querySelectorAll('.rowCheckbox');

        // 清除旧事件（防止重复绑定）
        if (selectAll) {
            selectAll.removeEventListener('change', handleSelectAll);
            selectAll.addEventListener('change', handleSelectAll);
        }

        rowCheckboxes.forEach(checkbox => {
            checkbox.removeEventListener('change', handleRowCheckbox);
            checkbox.addEventListener('change', handleRowCheckbox);
        });
    }

// 全选事件处理函数
    function handleSelectAll() {
        const isChecked = this.checked;
        document.querySelectorAll('.rowCheckbox').forEach(checkbox => {
            checkbox.checked = isChecked;
        });
    }

// 行复选框事件处理函数
    function handleRowCheckbox() {
        const allChecked = document.querySelectorAll('.rowCheckbox:checked').length ===
            document.querySelectorAll('.rowCheckbox').length;
        document.querySelector('.selectAll').checked = allChecked;
    }


    //禁言按钮
    function handleMuteUser($btn, userId) {
        // 获取按钮初始状态
        const initialStatus = $btn.text().trim();
        let isBanned = initialStatus === '禁言';
        // 初始化按钮样式
        updateButtonStyle($btn[0], isBanned);

        // 为单个按钮绑定点击事件
        $btn.click(function () {
            const action = isBanned ? '解禁' : '禁言';
            const apiUrl = isBanned
                ? `/admin/unMuteUser?id=${userId}`
                : `/admin/muteUser?id=${userId}`;
            confirms(`确定要${action}这个用户吗？`, (isConfirmed) => {
                if (isConfirmed) {
                    // 发送AJAX请求
                    $.ajax({
                        url: apiUrl,
                        type: 'GET',
                        success: function (response) {
                            console.log(18);
                            // 更新UI状态
                            isBanned = !isBanned;
                            updateButtonStyle(this, isBanned);
                            showCustomAlert(`${action}成功`, 3000);
                            location.reload();
                        },
                        error: function (error) {
                            console.error('AJAX请求失败:', error);
                            showCustomAlert(`${action}失败，请稍后再试`, 3000);
                        }
                    });
                }
            });
        })
    }

    const batchMuteBtn = document.getElementById('batchMuteall');
    batchMuteBtn.addEventListener('click', async function () {
        console.log(21);
        const checkedBoxes = document.querySelectorAll('.rowCheckbox:checked');
        const selectedUserIds = Array.from(checkedBoxes).map(checkbox =>
            checkbox.dataset.userId
        );

        if (checkedBoxes.length === 0) {
            showCustomAlert('请选择需要禁言的用户', 3000);
            return;
        }

        // 关键：将后续逻辑放入 confirms 的回调中
        confirms(`确定要禁言 ${checkedBoxes.length} 个用户吗？`, async (isConfirmed) => {
            if (!isConfirmed) {
                return; // 用户取消，直接返回
            }

            // 只有用户点击“确定”，才执行以下禁言逻辑
            this.disabled = true;
            this.textContent = '禁言中...';

            let successCount1 = 0;
            try {
                for (const userId of selectedUserIds) {
                    await $.ajax({
                        url: `/admin/muteUser?id=${userId}`,
                        method: 'GET',
                        dataType: 'text'
                    });
                    successCount1++;
                    const userRow = document.querySelector(`[data-user-id="${userId}"]`);
                    if (userRow) {
                        const statusButton = userRow.querySelector('.static');
                        updateButtonStyle(statusButton, true);
                    }
                }
                showCustomAlert(`成功禁言 ${successCount1} 个用户`, 3000);
            } catch (error) {
                console.error('批量禁言失败:', error);
                showCustomAlert(`禁言失败，已完成 ${successCount1} 个用户`, 3000);
            } finally {
                this.disabled = false;
                this.textContent = '禁言';
            }
        });
    });

    const batchUnmuteBtn = document.getElementById('batchUnmuteall');
    batchUnmuteBtn.addEventListener('click', async function () {
        const checkedBoxes = document.querySelectorAll('.rowCheckbox:checked');
        const selectedUserIds = Array.from(checkedBoxes).map(checkbox =>
            checkbox.dataset.userId
        );

        if (checkedBoxes.length === 0) {
            showCustomAlert('请选择需要解禁的用户');
            return;
        }
        confirms(`确定要解禁 ${checkedBoxes.length} 个用户吗？`, async (isConfirmed) => {
            if (!isConfirmed) {
                return;
            }

            this.disabled = true;
            this.textContent = '解禁中...';

            let successCount2 = 0;
            try {
                for (const userId of selectedUserIds) {
                    await $.ajax({
                        url: `/admin/unMuteUser?id=${userId}`,
                        method: 'GET',
                        dataType: 'text'
                    });

                    const userRow = document.querySelector(`[data-user-id="${userId}"]`);
                    if (userRow) {
                        const statusButton = userRow.querySelector('.static');
                        statusButton.textContent = '正常';
                        updateButtonStyle(statusButton, false);
                        successCount2++;
                    }
                }

                showCustomAlert(`成功解禁 ${successCount2} 个用户`, 3000);
            } catch (error) {
                console.error('批量解禁失败:', error);
                showCustomAlert(`解禁失败，已完成 ${successCount2} 个用户，剩余操作终止`, 3000);
            } finally {
                this.disabled = false;
                this.textContent = '解禁';
            }
        });
    })

// 更新按钮样式的辅助函数（移到全局作用域）
    function updateButtonStyle(button, isBanned) {
        button.textContent = isBanned ? '禁言' : '正常';
    }

// 返回表单
    const backform = document.getElementById('backform');
    backform.addEventListener('click', function () {
        location.reload();
    });

// //删除用户
    function handleDeleteUser($btn, userId) {
        const button = $(this); // 保存当前按钮的引用
        confirms('确定要删除该用户吗？', (isConfirmed) => {
            if (isConfirmed) {
                $.ajax({
                    url: `http://localhost:8080/admin/toDeleteUser`,
                    method: 'GET',
                    // 添加data参数
                    data: {id: userId},
                    // 指定返回类型
                    dataType: 'text',
                    success: function (response) {
                        button.closest('tr').remove();
                        // 重新加载数据（适用于分页场景）
                        location.reload();
                        showCustomAlert('删除成功');
                    },
                    error: function (error) {
                        console.log('删除用户失败:', error);
                        showCustomAlert('删除用户失败，请重试', 3000);
                        console.log(this.url);
                    }
                });
            }
        })
    }

    // 批量删除功能（适配单接口）
    const deleteAll = document.getElementById("check-button");
    deleteAll.addEventListener('click', function () {
        const checkedBoxes = $('.rowCheckbox:checked');

        if (checkedBoxes.length === 0) {
            showCustomAlert('请先选择要删除的用户', 3000);
            return;
        }
        confirms(`确定要删除选中的 ${checkedBoxes.length} 个用户吗？`, (isConfirmed) => {
            if (!isConfirmed) {
                return;
            }

            // 逐个调用单个删除接口
            let deletedCount = 0;
            const userIds = checkedBoxes.map(function () {
                return $(this).data('user-id'); // 直接获取复选框的data-user-id（需确保HTML中存在）
            }).get();
            console.log(11)
            // 禁用按钮防止重复提交
            $(this).prop('disabled', true).text('删除中...');

            // 循环发送请求（使用async/await处理异步流程）
            (async function () {
                try {
                    for (const userId of userIds) {
                        // 调用单个删除接口
                        const response = await $.ajax({
                            url: `http://localhost:8080/admin/toDeleteUser`,
                            method: 'GET',
                            data: {id: userId},
                            dataType: 'text'
                        });
                        deletedCount++;
                        // 移除对应的表格行
                        $(`tr[data-user-id="${userId}"]`).remove();
                        console.log(userId);
                        location.reload();

                    }
                    showCustomAlert(`成功删除 ${deletedCount} 个用户`);
                } catch (error) {
                    console.error('批量删除失败:', error);
                    showCustomAlert(`删除过程中出错，已成功删除 ${deletedCount} 个用户，剩余操作未完成`);
                } finally {
                    // 恢复按钮状态
                    $('#check-button').prop('disabled', false).text('全部删除');
                }
            })();
        });
    });
})
    //添加
    const addbtn = document.querySelector(' .add-button');
    const addModal = document.getElementById('addModal1');
    const cancel = document.getElementById('cancelEditPost1');
    const confirmss = document.getElementById('userEditModalSaveButton1');

    cancel.addEventListener('click', function () {
        addModal.style.display = 'none';
        document.getElementById('userNamePostTitle').value = '';
        document.getElementById('userEmail').value = '';
        document.getElementById('userPassword').value= '';
        document.getElementById("userGender").value= '';
    });
    addbtn.addEventListener('click', function () {
        addModal.style.display = 'block';
    });

    confirmss.addEventListener('click', function () {
        console.log("添加")
        const gender = document.getElementById("userGender").value;
        const name = document.getElementById("userNamePostTitle1").value;
        const email = document.getElementById("userEmail1").value;
        const password = document.getElementById('userPassword').value;

        const filteredName = name.replace(/<[^>]*>/g, '');
        const filteredEmail = email.replace(/<[^>]*>/g, '');
        const filteredPassword = password.replace(/<[^>]*>/g, ''); // 新增密码过滤

        // **关键修正：先执行校验，再发送请求**
        if (!validateInput(filteredName, filteredEmail, filteredPassword)) { // 传递所有需要校验的参数
            return; // 校验不通过，终止后续操作
        }

            var params = $.param({
                username: name,
                email: filteredEmail,
                bio: 'unknown',
                industry: 'unknown',
                location: 'unknown',
                shortBio: 'unknown',
                password: password,
                avatar: 'unknown',
                gender: gender
            });
            console.log(21);
            $.ajax({
                type: 'POST',
                url: `http://localhost:8080/admin/toAddUser`,
                data: params, // 修改为对象形式
                success: function (result) {
                    console.log(25);
                    showCustomAlert('确定添加？');
                    location.reload()
                    addModal.style.display = 'none';
                },
                error: function (result) {
                    addModal.style.display = 'none';
                    document.getElementById('userNamePostTitle1').value = '';
                    document.getElementById('userEmail1').value = '';
                    document.getElementById('userPassword').value = '';
                    document.getElementById("userGender").value = '';
                    console.log(result);
                    // 显示失败提示
                    addModal.style.display = 'none';
                    showCustomAlert('该用户添加失败', 3000);
                }
            });
    });
    function validateInput(name, email) {
        let isValid = true;
        const nameError = document.getElementById('nameError');
        const password = document.getElementById('userPassword').value;
        // const timeError = document.getElementById('timeError');
        const emailError = document.getElementById('emailError');
        const passwordError = document.getElementById('passwordError');
        if (name === '') {
            nameError.textContent = '昵称不能为空';
            isValid = false;
        }
        if (email === '') {
            emailError.textContent = '邮箱不能为空';
            isValid = false;
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            emailError.textContent = '请输入有效的邮箱地址';
            isValid = false;
        }
        if (!password) {
            passwordError.textContent = '密码不能为空';
            isValid = false;
        } else {
            const MIN_LENGTH = 8;
            const MAX_LENGTH = 20;
            const COMPLEXITY_REGEX = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
            if (password.length < MIN_LENGTH) {
                passwordError.textContent = `密码长度不能少于${MIN_LENGTH}个字符`;
                isValid = false;
            } else if (password.length > MAX_LENGTH) {
                passwordError.textContent = `密码长度不能超过${MAX_LENGTH}个字符`;
                isValid = false;
            } else if (!COMPLEXITY_REGEX.test(password)) {
                passwordError.textContent = '密码必须包含大小写字母、数字和特殊字符';
                isValid = false;
            }
            return isValid;
        }
        //弹窗
        function Alert(message, duration) {
            const alertDiv = document.createElement('div');
            alertDiv.style.position = 'fixed';
            alertDiv.style.top = '12px';
            alertDiv.style.right = '499px';
            alertDiv.style.backgroundColor = '#333';
            alertDiv.style.color = 'white';
            alertDiv.style.padding = '10px';
            alertDiv.style.borderRadius = '5px';
            alertDiv.style.boxShadow = '0 0 5px rgba(0, 0, 0, 0.3)';
            alertDiv.style.zIndex = '1000';
            alertDiv.style.opacity = '0';
            alertDiv.style.width = '300px';
            alertDiv.style.textAlign = 'center';
            alertDiv.style.transition = 'opacity 0.3s ease-in-out';
            alertDiv.textContent = message;

            document.body.appendChild(alertDiv);

            alertDiv.style.opacity = '1';

            setTimeout(() => {
                alertDiv.style.opacity = '0';
                setTimeout(() => {
                    document.body.removeChild(alertDiv);
                }, 3000);
            }, duration);
        }
    }
    //获取编辑id信息
    document.getElementById('avatarUpload').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('newimg').src = e.target.result;
                document.getElementById('newimg').style.display = 'block';
            }
            reader.readAsDataURL(file);
        }
    });
    //编辑
    function handleEditUser(userId) {
        const userEditModal = document.getElementById('userEditModal')
        const editButtons = document.querySelectorAll('.editbtn');
        editButtons.forEach(button => {
            button.addEventListener('click', function () {
                // 检查this是否指向正确的DOM元素
                console.log('this:', this);

                // 使用dataset获取用户ID
                const userId = this.dataset.userId;
                console.log('userId:', userId);
                // 获取当前点击按钮的用户ID
                userEditModal.style.display = 'block';
                console.log('编辑用户ID:', userId); // 用于调试

                if (!userId) {
                    showCustomAlert('无效的用户ID');
                    return;
                }
                const url = `http://localhost:8080/admin/toUpdateUserPage?id=${userId}`;
                // 使用AJAX获取用户数据
                $.ajax({
                    dataType: 'json', // 明确指定返回JSON格式
                    url: url,
                    method: 'GET',
                    success: function (user) {
                        console.log('获取用户数据成功:', user); // 用于调试
                        // 填充表单数据
                        document.getElementById('userNamePostTitle').value = user.user.username;
                        document.getElementById('userEmail').value = user.user.email;
                        document.getElementById('userAddress').value = user.user.location;
                        document.getElementById('userGenders').value = user.user.gender;
                        document.getElementById('userIndustry').value = user.user.industry;
                        document.getElementById('userBriefIntro').value = user.user.shortBio;
                        document.getElementById('userIntroduction').value = user.user.bio;
                        document.getElementById('passwordPostTitle').value = user.user.password;
                        document.getElementById('newimg').src = user.user.avatar;
                        // 保存用户ID到保存按钮的dataset中
                        document.getElementById('userEditModalSaveButton').dataset.userId = userId;
                        // 显示编辑模态框
                        document.getElementById('userEditModal').style.display = 'block';
                    },
                    error: function (error) {
                        console.error('请求出错:', error);
                        showCustomAlert('请求出错，请稍后重试',3000);
                    }
                });
            });
        });
    }
        // 保存按钮的点击事件
        document.getElementById('userEditModalSaveButton').addEventListener('click', function(e) {
            e.preventDefault();

            // 从保存按钮的dataset中获取用户ID
            // 获取用户ID
            const id = document.getElementById('userEditModalSaveButton').dataset.userId;
            console.log('保存用户ID:', id);

// 获取表单数据
            const password = document.getElementById('passwordPostTitle').value;
            const name = document.getElementById('userNamePostTitle').value;
            const email = document.getElementById('userEmail').value;
            const location = document.getElementById('userAddress').value;
            const gender = document.getElementById('userGenders').value;
            const industry = document.getElementById('userIndustry').value;
            const shortBio = document.getElementById('userBriefIntro').value;
            const bio = document.getElementById('userIntroduction').value;
            const img = document.getElementById('newimg').src;

// 验证必要字段
            if (!password || !name || !email) {
                showCustomAlert('用户名、密码和邮箱不能为空',3000);
                return;
            }

            const urlParams = new URLSearchParams({
                id: id,
                username: name,
                password: password,
                email: email,
                avatar: img,
                gender: gender,
                location: location,
                industry: industry,
                shortBio: shortBio,
                bio: bio,
                // 移除createdAt，因为注册时间通常不应该被修改
                // createdAt: registerTime
            }).toString();

            console.log('更新用户参数:', urlParams);

            $.ajax({
                url: `http://localhost:8080/admin/toUpdateUser?${urlParams}`,
                method: 'POST',
                success: function(response) {
                    console.log('保存结果:', response); // 用于调试
                    showCustomAlert('编辑成功');
                        document.getElementById('userEditModal').style.display = 'none';
                        // 刷新表格数据
                        window.location.reload();
                },
                error: function(error) {
                    console.error('请求出错:', error);
                    showCustomAlert('请求出错，请稍后重试',3000);
                }
            });
        });

        // 取消按钮的点击事件
        document.querySelector('.cancelEditPost1').addEventListener('click', function() {
            document.getElementById('userEditModal').style.display = 'none';
        });
